window.onload = function () {
  const playerAudio = document.getElementById('player-audio')
  const unlockAudio = document.getElementById('unlock-audio')
  const statusEl = document.getElementById('player-status')
  let audioUnlocked = false

  const unlockAudioPolicy = async () => {
    if (audioUnlocked) return
    try {
      await unlockAudio.play()
      unlockAudio.pause()
      audioUnlocked = true
      statusEl.textContent = '音频已解锁，等待播放指令...'
    } catch (err) {
      statusEl.textContent = '音频解锁失败，请点击页面重试。'
    }
  }

  document.addEventListener('click', unlockAudioPolicy, {once: true})

  const worker = new SharedWorker('shareworker.js')

  worker.port.onmessage = async e => {
    if (e.data.type === 'switch') {
      if (!audioUnlocked) {
        statusEl.textContent = '请先点击页面任意位置以允许音频播放。'
        await unlockAudioPolicy()
        if (!audioUnlocked) return
      }

      const musicUrl = e.data.music
      playerAudio.src = musicUrl
      const musicName = musicUrl.split('/').pop()

      try {
        await playerAudio.play()
        statusEl.textContent = `正在播放: ${musicName}`
        worker.port.postMessage({type: 'play', music: musicUrl})
      } catch (err) {
        statusEl.textContent = `播放失败: ${musicName}`
        audioUnlocked = false
      }
    }
  }

  worker.port.start()
}
